package com.ruoyi.system.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.domain.SysDomainName;
import com.ruoyi.system.mapper.SysDomainNameMapper;
import com.ruoyi.system.utils.HttpsUtlis;
import com.ruoyi.system.utils.MessageNotification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 定时获取域名节点数据
 */
@Service("DetectRedNameJob")
public class DetectRedNameJob {

    @Resource
    private SysDomainNameMapper sysDomainNameMapper;

    @Resource
    private HttpsUtlis httpsUtlis;

    @Resource
    private MessageNotification messageNotification;


    /**
     * 定时获取域名节点数据
     */
    public void domainName() {
        // 创建一个线程池，大小可以根据需要调整
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<SysDomainName> sysDomainNames = sysDomainNameMapper.selectList(new LambdaQueryWrapper<SysDomainName>()
                .eq(SysDomainName::getDeleted, 0).eq(SysDomainName::getStatus, 0));
        // 创建一个列表用于存储任务的 Future 对象
        List<Future<Void>> futures = new ArrayList<>();
        for (SysDomainName domainName : sysDomainNames) {
            // 提交每个任务到线程池
            Future<Void> future = executorService.submit(() -> {
                int threshold = httpsUtlis.create(domainName.getDomainName());
                if (threshold == 0 || domainName.getThreshold() == 0) {
                    // 可以在这里记录日志，跳过通知
                    System.out.println("Threshold is zero, skipping notification for domain: " + domainName.getDomainName());
                } else if (threshold >= domainName.getThreshold()) {
                    // 发送通知（根据业务逻辑执行通知）
                    sendNotification(domainName, threshold);
                }
                return null;  // 返回 Void
            });
            futures.add(future);
        }
        // 等待所有任务完成
        for (Future<Void> future : futures) {
            try {
                future.get();  // 阻塞等待每个任务完成
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();  // 处理任务异常
            }
        }
        // 关闭线程池
        executorService.shutdown();
    }

    private void sendNotification(SysDomainName domainName,Integer threshold) {
        messageNotification.Message(domainName.getDomainName(),threshold);
    }

}
